import SiteConfig from '../models/SiteConfig'

export interface IModelConfig {
    id: number
    sdk: string
    name: string
    model: string
    apiKey: string
    baseURL: string
    type: 'chat' | 'embed'
}

export interface IUrlConfig {
    uploadBaseUrl: string
    chromaUrl: string
}

export interface IRuntimeConfig {
    caseChatModel: IModelConfig
    writingChatModel: IModelConfig
    urlConfigs: IUrlConfig
}

export const defaultConfig: IRuntimeConfig = {
    caseChatModel: {
        id: 1,
        sdk: 'ollama',
        name: '本地-千问',
        model: 'qwen2.5:1.5b',
        apiKey: '',
        baseURL: '',
        type: 'chat',
    },
    writingChatModel: {
        id: 2,
        sdk: 'ollama',
        name: '本地-千问',
        model: 'qwen2.5:1.5b',
        apiKey: '',
        baseURL: '',
        type: 'chat',
    },
    urlConfigs: {
        uploadBaseUrl: '/api',
        chromaUrl: 'http://127.0.0.1:8000',
    },
}

export type IModelConfigItem =
    (typeof defaultConfig)[keyof typeof defaultConfig]

export let runtimeConfig: typeof defaultConfig = defaultConfig

export const updateRuntimeConfigFromDB = async () => {
    try {
        const config = await SiteConfig.findAll()
        config.forEach((item) => {
            const key = item.configKey as keyof typeof defaultConfig
            runtimeConfig[key] = item.configValue
        })
    } catch (error) {
        console.log(error)
    }
}

// 当数据库为空时，初始化数据
export const initSiteConfigDB = async () => {
    const keys = Object.keys(defaultConfig)
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i] as keyof typeof defaultConfig
        await SiteConfig.findOrCreate({
            where: {
                configKey: key,
            },
            defaults: {
                configKey: key,
                configValue: defaultConfig[key],
            },
        })
    }
}

updateRuntimeConfigFromDB()
// initSiteConfigDB()
